package cn.edu.suda.catalina.utils;

import io.appium.java_client.AppiumDriver;
import io.appium.java_client.android.AndroidDriver;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by admin on 2016/12/20.
 */
public class SessionUtils {

    protected AppiumDriver<WebElement> driver;

    public SessionUtils() {
        driver = null;
    }

    public SessionUtils(String appPath, String appName, String appPackage, String appActivity) {
        if (test(appPath) && test(appName) && test(appPackage) && test(appActivity)) {
            File appDir = new File(appPath);
            File app = new File(appDir, appName);
            DesiredCapabilities capabilities = new DesiredCapabilities();
            capabilities.setCapability("deviceName", "emulator android");
            capabilities.setCapability("platformVersion", "6.0");
            capabilities.setCapability("platformName", "Android");
            capabilities.setCapability("noSign", "True");
            capabilities.setCapability("unicodeKeyboard", "True");
            capabilities.setCapability("resetKeyboard", "True");
            capabilities.setCapability("clearSystemFiles", "True");
            capabilities.setCapability("autoLaunch", "False");
            capabilities.setCapability("app", app.getAbsolutePath());
            capabilities.setCapability("appPackage", appPackage);
            capabilities.setCapability("appActivity", appActivity);
            try {
                driver = new AndroidDriver<>(new URL("http://localhost:4723/wd/hub"), capabilities);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
        }
    }

    protected boolean test(String path) {
        return !(path == null || path.isEmpty());
    }

    //释放session
    public void tearDown() {
        driver.quit();
    }

    /**
     * ndroid屏幕截图
     * @param pathname
     */
    public void Screenshot(String pathname) {
        if (test(pathname)) {
            File file = driver.getScreenshotAs(OutputType.FILE);
            try {
                FileUtils.copyFile(file, new File(pathname));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
